const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const moment = require('../../lib/moment/moment.min.js');
import WxValidate from '../../lib/wx-validate/WxValidate.js'
//获取应用实例
const app = getApp();
var page;
var that;
Page({
  data: {
    scrollTop: 0,
    tabs: [{ text: '申请报修', active: true }, { text: '报修记录', active: false }],
    tabIndex: 0,
    form:{
      unitName:'',
      houseName:'',
      content: '',
      photoUrl:'',
    },
    picUrls: [],
    files: [],
    oldFps:[],
    isLoadRepairs: false, //是否加载
    records: [],
    isLoadUFR: false, //是否加载了房东的单元信息
    ufroom: [],
    units: [],
    floors: [],
    rooms: [],
    unitIndex: 0,
    floorIndex: 0,
    roomsIndex: 0,
    multiArray: [],
    multiIndex: [0, 0, 0],
    unitDisabled:false,
    houseDisabled:false,
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    that.initValidate();
    page = util.page.clone();
    if(options.unitName){
      that.setData({
        'form.unitName':options.unitName,
        unitDisabled: true,
      });
    }
    if (options.houseName) {
      that.setData({
        'form.houseName': options.houseName,
        houseDisabled: true,
      });
    }
  },
  onReady: function () {},
  onShow: function () {
  },
  toDoRepairs: function () { //查询报修记录
    let params = {};
    app.loadPageExt(api.GetRepairs, page, params).then(rsp => {
      //console.log('rspppppp',rsp);
      var records = rsp;
      if (records.length>0){
        records.forEach(function (i, n) {
          if (i.photoUrl && i.photoUrl.indexOf('/') != -1) {
            i.imgs = i.photoUrl.split(',').map(function (v, k) {
              return app.showImg(v);
            });
            i.showTime = moment(i.createTime).format('YYYY-M-DD')
          }
          that.data.records.push(i);
        });
      }
      
      that.setData({ records: that.data.records,isLoadRepairs: true });
    }).catch((err) => {
      console.log(err);
    });
  },
  onPullDownRefresh() {
    if (that.data.tabIndex == 1) {
      page.reset();
      that.setData({
        records: []
      });
      that.toDoRepairs();
    }
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
    if (that.data.tabIndex == 1) {
      that.toDoRepairs();
    }
  },
  resetData(){
    Object.keys(that.data.form).forEach(function (k, n) {
      that.data.form[k] = '';
    });
    that.setData({
      form: that.data.form,
      picUrls: [],
      files: [],
      oldFps: [],
    });
    this.commonTab(1);
    that.onPullDownRefresh();
  },
  delFiles(urls) {
    app.removeFiles(urls, api.RemoveImgOss);
  },
  submitForm: function (e) {
    const params = e.detail.value
    //console.log(params)
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      util.toast.pure(error.msg);
      return false
    }
    var form = JSON.parse(JSON.stringify(that.data.form));
    //图片地址整理
    util.confirm.openExt('您确定好了吗？', function () {
      util.toast.loading('数据提交中...', 60);
      var upFs = that.data.files.slice(0);
      var urls = []; //数据提交失败则删除已上传的文件,避免资源占用
      app.uploads(upFs, api.UploadImgOss).then(arr => {
        //console.log('arrrrrrrrrrrr', arr);
        if (arr.length > 0) {
          form.photoUrl = arr.map(function (f, n) {
            urls.push(f.filePath);
            return f.filePath;
          }).join(',');
        }
        if (form.photoUrl.indexOf(',') == 0) {
          form.photoUrl = form.photoUrl.substring(1);
        }
        app.postPure(api.CommitRepair, form).then(rsp => {
          util.toast.success('申请成功!');
          that.resetData();
        }).catch((err) => {
          that.setData({ tabIndex: 1 });
          that.delFiles(urls);
          console.log(err);
        });
      });
    });
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      unitName: {
        required: true,
      },
      houseName: {
        required: true,
      },
      content: {
        required: true,
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      unitName: {
        required: '请输入楼层号',
      },
      houseName: {
        required: '请输入房间号',
      },
      content: {
        required: '请输入设备损坏情况',
      }
    }
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  previewRecordImage: function (e) {
    let ifx = e.currentTarget.dataset.ifx;
    let urls = that.data.records[ifx].imgs;
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  chooseImage: function (e) {
    if (that.data.files.length > 3) {
      util.toast.fail('最多只能上传3张图片')
      return false;
    }
    wx.showActionSheet({
      itemList: ['上传照片', '追加上传'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            wx.chooseImage({
              count: 6,
              sizeType: ['original', 'compressed'],
              sourceType: ['album', 'camera'],
              success: function (res) {
                //保存旧有的图片路径
                var oldFps = that.data.files.concat();
                that.setData({
                  files: [].concat(res.tempFilePaths),
                  oldFps: oldFps,
                  isAppendUp: false
                });
              }
            });
          } else {
            wx.chooseImage({
              count: 6,
              sizeType: ['original', 'compressed'],
              sourceType: ['album', 'camera'],
              success: function (res) {
                if ((that.data.files.length + res.tempFilePaths.length) > 3) {
                  util.toast.fail('最多只能上传3张图片')
                } else {
                  that.setData({
                    files: that.data.files.concat(res.tempFilePaths),
                    isAppendUp: true,
                  });
                }
              }
            });
          }
        }
      }
    });
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.files // 需要预览的图片http链接列表
    })
  },
  delRoomFile: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    //console.log('index' + index);
    that.setData({
      files: util.arrayUtil.delByIndex(that.data.files, index)
    });
  },
  bindInput: function (e) {
    let name = e.currentTarget.dataset.name;
    let changeVal = {};
    changeVal[name] = e.detail.value;
    this.setData(changeVal);
  },
  bindInputValue(event) {
    let value = event.detail.value;
    this.setData({
      'form.content': event.detail.value,
    })
  },
  commonTab: function (index) {
    this.data.tabs.forEach(function (n, i) {
      if (index == i) {
        n.active = true;
      } else {
        n.active = false;
      }
    });
    this.setData({ tabs: this.data.tabs, tabIndex: index });
  },
  selTab: function (e) {
    let index = e.currentTarget.dataset.index;
    that.tabChange({ detail: { current: index } });
  },
  tabChange: function (e) {
    let index = e.detail.current;
    this.commonTab(index);
    if (index == 1 && !that.data.isLoadRepairs) {
      that.toDoRepairs();
    }
  },
  initUFR() {
    if (that.data.isLoadUFR) return false;
    app.postForm(api.GetAllUnitInfo, { ownersNo: app.globalData.ownersNo, isAllow: true, retry: 3 }).then(res => {
      if (res.data) {
        that.setData({
          isLoadUFR: true,
          ufroom: res.data
        });
        var ufroom = that.data.ufroom;
        //楼号初始化
        ufroom.forEach(function (i, n) {
          that.data.units.push(i.unitName + '号楼');
        });
        var floors = ufroom[that.data.unitIndex].floors;
        if (floors) {
          //楼层初始化
          floors.forEach(function (i, n) {
            that.data.floors.push((n + 1) + '层');
          });
        }
        ufroom[that.data.unitIndex].floors[0].forEach(function (i, n) {
          Object.keys(i).forEach(function (name) {
            that.data.rooms.push(name + '号');
          });
        });
        that.data.multiArray.push(that.data.units);
        that.data.multiArray.push(that.data.floors);
        that.data.multiArray.push(that.data.rooms);
        that.setData({
          multiArray: that.data.multiArray,
          'form.unitName': that.data.multiArray[0][that.data.multiIndex[0]].replace('号楼', ''),
          'form.houseName': that.data.multiArray[2][that.data.multiIndex[2]].replace('号', ''),
          unitId: ufroom[that.data.multiIndex[0]].id
        });
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  bindMultiPickerColumnChange: function (e) {
    //console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: that.data.multiArray,
      multiIndex: that.data.multiIndex
    };
    var ufroom = that.data.ufroom;
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        that.setData({
          floors: [],
          rooms: [],
          floorIndex: 0,
          roomsIndex: 0
        });
        //楼层初始化
        var floors = ufroom[data.multiIndex[0]].floors;
        if (floors) {
          floors.forEach(function (i, n) {
            that.data.floors.push((n + 1) + '层');
          });
          //房号初始化
          floors[that.data.floorIndex].forEach(function (i, n) {
            Object.keys(i).forEach(function (name) {
              that.data.rooms.push(name + '号');
            });
          });
          data.multiArray[1] = that.data.floors;
          data.multiArray[2] = that.data.rooms;
        }
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        break;
      case 1:
        that.setData({
          rooms: [],
          roomsIndex: 0
        });
        //房号初始化
        ufroom[data.multiIndex[0]].floors[data.multiIndex[1]].forEach(function (i, n) {
          Object.keys(i).forEach(function (name) {
            that.data.rooms.push(name + '号');
          });
        });
        data.multiArray[2] = that.data.rooms;
        data.multiIndex[2] = 0;
        break;
    }
    that.setData(data);
    that.setData({
      'form.unitName': data.multiArray[0][data.multiIndex[0]].replace('号楼', ''),
      'form.houseName': data.multiArray[2][data.multiIndex[2]].replace('号', ''),
      unitId: ufroom[data.multiIndex[0]].id
    });
  },
})